package com.banch.cloud.payment.controller;

import com.banch.cloud.common.entity.Payment;
import com.banch.cloud.common.vo.CommonResult;
import com.banch.cloud.payment.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * payment controller
 *
 * @author banch
 * @version 1.0
 * @date 2020/5/5
 */
@Slf4j
@RestController
@RequestMapping(value = {"/payment"})
public class PaymentController {

    /**
     * payment Service
     */
    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    /**
     * 插入支付记录
     *
     * @param payment Payment
     * @return
     * @author banch
     * @date 2020/5/5
     * @throw
     **/
    @PostMapping(value = {"/create"}, consumes = {MediaType.APPLICATION_JSON_VALUE})
    public CommonResult create(@RequestBody Payment payment) {

        int result = paymentService.create(payment);
        log.info("create result:{}", result);

        if (result > 0) {
            return new CommonResult(200, "插入数据库成功，serverPort:" + serverPort, result);
        } else {
            return new CommonResult(400, "插入数据库失败，serverPort:" + serverPort, null);
        }
    }

    /**
     * get by id
     *
     * @param id id
     * @return
     * @author banch
     * @date 2020/5/5
     * @throw
     **/
    @GetMapping(value = {"/get/{id}"})
    public CommonResult getById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getById(id);
        log.info("get result:{}", payment);
        if (payment != null) {
            return new CommonResult(200, "查询成功，serverPort:" + serverPort, payment);
        } else {
            return new CommonResult(400, "没有对应记录,serverPort:" + serverPort + ",id:" + id, null);
        }
    }


    @GetMapping(value = {"/discovery"})
    public Object discovery() {

        List<String> services = discoveryClient.getServices();
        for (String servie : services) {
            log.info("****service:" + servie);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");

        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId() + "\t" + instance.getInstanceId() + "\t"
                    + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
        }

        return discoveryClient;
    }

}